package com.xudow.app.newui;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.v7.app.AlertDialog;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.activeshare.edu.ucenter.common.messages.user.UserDetailMessage;
import com.activeshare.edu.ucenter.models.user.UserProfileWithOther;
import com.umeng.message.PushAgent;
import com.xudow.app.Config;
import com.xudow.app.R;
import com.xudow.app.Version;
import com.xudow.app.XApplication;
import com.xudow.app.dynamicstate_old.data.DynamicModel;
import com.xudow.app.dynamicstate_old.data.server.ErrorTransform;
import com.xudow.app.dynamicstate_old.module.guide.ClazzActivity;
import com.xudow.app.newui.home.HomeActivity;
import com.xudow.app.ui.BaseActivity;
import com.xudow.app.ui.ForgetPasswordActivity;
import com.xudow.app.ui.MobilePhoneBindActivity;
import com.xudow.app.ui.RegisterActivity;
import com.xudow.app.ui.task.LoginTask;
import com.xudow.app.ui.task.UserProfileTask;
import com.xudow.app.util.Maps;
import com.xudow.app.util.StringUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import static com.xudow.app.util.LogUtils.makeLogTag;

/**
 * 机构登录
 * Login activity
 *
 * @author lukecheng
 */
public class AgencyUserLoginActivity extends BaseActivity  {
    private final static String TAG = makeLogTag(AgencyUserLoginActivity.class);

    /**
     * 密码是否可见
     */
    private boolean isPasswordVisibled = false;

    private EditText usernameEditText;
    private EditText passwordEditText;

    private LoginTask loginTask;
    private UserProfileTask userProfileTask;
    private boolean closeAfterLogin = false;  //登录完成后直接关闭，不跳转到其他Activity
    private boolean gotohome = false;//登录后进入主页面

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_agency_login);
        ((TextView)findViewById(R.id.title)).setText("机构登录");
        usernameEditText = (EditText) findViewById(R.id.username);
        passwordEditText = (EditText) findViewById(R.id.password);


        if (!Version.PUBLIC_VERSION) {
            findViewById(R.id.register_link).setVisibility(View.GONE);
            //findViewById(R.id.register_link_sep).setVisibility(View.GONE);
        }

        closeAfterLogin = getIntent().getBooleanExtra("closeAfterLogin", false);
        gotohome = getIntent().getBooleanExtra("GOTOHOME", false);
    }

    /**
     * 修改密码输入框的可见性
     *
     * @param view
     */
    public void switchPasswordEditMode(View view) {
        ImageView switchView = (ImageView) view;

        if (isPasswordVisibled) {
            passwordEditText.setInputType(InputType.TYPE_CLASS_TEXT
                    | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            switchView.setImageResource(R.mipmap.ico_password_invisible);
            isPasswordVisibled = false;
        } else {
            passwordEditText.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            switchView.setImageResource(R.mipmap.ico_password_visible);
            isPasswordVisibled = true;
        }
    }

    /**
     * 返回点击事件
     *
     * @param view
     */
    public void onBackBtnClick(View view) {
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode && null != loginTask && !loginTask.isCancelled()) {
            loginTask.cancel(true);
            loginTask = null;
        }
        if (gotohome) {//重退出登录界面转入 back键关闭application
            sendExitBroadcast();
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 登陆按钮点击事件
     *
     * @param view
     */
    public void onLoginClick(View view) {
        String username = usernameEditText.getText().toString().trim();
        if (StringUtils.isEmpty(username)) {
            usernameEditText.setError(getResources().getString(R.string.username_required));
            return;
        }

        String password = passwordEditText.getText().toString().trim();
        if (StringUtils.isEmpty(password)) {
            passwordEditText.setError("密码不能为空");
            return;
        }

        HashMap<String, String> params = Maps.newHashMap();
        params.put("username", username);
        params.put("password", password);

        showLodingDialog(getString(R.string.login_prompt));

        loginTask = new LoginTask(this, loginHandler);
        addTask(loginTask);
        loginTask.execute(params);
    }

    /**
     * 登陆处理Handler
     */
    private Handler loginHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            hideLoadingDialog();

            if (LoginTask.LOGIN_SUCCESS == msg.what) {
//                if (!XApplication.getInstance().isHasAttentionType()) {
                    String grade = PreferenceManager.getDefaultSharedPreferences(AgencyUserLoginActivity.this).getString("Grade", "[]");
                    String attentions = PreferenceManager.getDefaultSharedPreferences(AgencyUserLoginActivity.this).getString("attentiontype", "[]");
                    try {
                        JSONArray array1 = new JSONArray(grade);
                        for (int i = 0; i < array1.length(); i++) {
                            JSONObject o = (JSONObject) array1.get(i);
//                            o.remove("name");
                            o.remove("selected");
//                            o.remove("name");
                        }
                        grade = array1.toString();
                        JSONArray array2 = new JSONArray(attentions);
                        for (int i = 0; i < array2.length(); i++) {
                            JSONObject o = (JSONObject) array2.get(i);
//                            o.remove("name");
                            o.remove("createTime");
                        }
                        attentions = array2.toString();

                    } catch (JSONException e) {
                    }
                    DynamicModel.getInstance().submitUserAttention(grade, attentions)
                            .compose(new ErrorTransform<>(ErrorTransform.ServerErrorHandler.NONE))
                            .subscribe();
//                }
                userProfileTask = new UserProfileTask(AgencyUserLoginActivity.this, userprofileHandler);
                addTask(userProfileTask);
                userProfileTask.execute();
            } else if (LoginTask.LOGIN_FAIL == msg.what) {
                Bundle bundle = msg.getData();
                String errMsg = bundle.getString("errorMessage");

                Toast.makeText(AgencyUserLoginActivity.this, errMsg, Toast.LENGTH_LONG).show();
            } else {
                String toastMsg = getString(R.string.common_fail_connect_server);
                Toast.makeText(AgencyUserLoginActivity.this, toastMsg, Toast.LENGTH_LONG).show();
            }
        }
    };

    /**
     * 用户基本信息Handler
     */
    private Handler userprofileHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (UserProfileTask.SUCCESS == msg.what) {
                Bundle data = msg.getData();
                UserDetailMessage ud = (UserDetailMessage) data.getSerializable("profile");
                UserProfileWithOther profile = ud.getUserDetail();

                try {
                    PushAgent.getInstance(AgencyUserLoginActivity.this).addAlias(profile.getName(), Config.XUDOW_UMENG_MSG_ALIAS);
                    PushAgent.getInstance(AgencyUserLoginActivity.this).addExclusiveAlias(profile.getName(), Config.XUDOW_UMENG_MSG_ALIAS);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                XApplication application = (XApplication) getApplication();
                application.setUserProfileId(profile.getId());
                application.setProfile(profile);
                //用户必须绑定手机号
                if (StringUtils.isEmpty(profile.getMobilePhone())) {
                    startActivity(new Intent(AgencyUserLoginActivity.this, MobilePhoneBindActivity.class));
                } else if (!XApplication.getInstance().isHasAttentionType()) {
                    Intent intent = new Intent(AgencyUserLoginActivity.this, ClazzActivity.class);
                    intent.putExtra("isLogin", true);
                    startActivity(intent);
                }
                if (gotohome) {
                    startActivity(new Intent(AgencyUserLoginActivity.this, HomeActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
                }


                finish();
            } else {
                //TODO:获取用户信息失败处理
            }
        }
    };

}
